<template>
    <el-container>
        <el-header>
            <div class="el-header-left">
                <el-button type="primary" :icon="CirclePlus" class="el-button--primary-i"
                    @click="handleAdd">新增</el-button>
                <el-button type="info" :icon="Upload" @click="handleUpload">导入</el-button>
                <el-button type="info" :icon="Download" @click="handleDownload(scope, 'file')">导出</el-button>
                <el-button type="info" :icon="Download" @click="handleDownload(scope, 'template')">下载模板</el-button>
                <el-button type="info" :icon="Delete" @click="handleDelete()"
                    v-if="multipleSelection.length > 0">删除</el-button>
            </div>
            <div class="el-header-right">
                <el-button type="primary" link :icon="Sort">排序</el-button>
                <el-button type="primary" link :icon="RefreshRight" @click="handleRefresh">刷新</el-button>
            </div>
        </el-header>
        <el-main>
            <el-config-provider :locale="zhCn">
                <el-table ref="multipleTableRef" :data="lowCodeStore.listAllData.tableData" style="width: 100%"
                    :height="tableHeight" @selection-change="onSelectionChange">

                    <el-table-column type="selection" width="55" />

                    <el-table-column v-for="column in tableColumns" :key="column.prop" :property="column.prop"
                        :label="column.label">
                    </el-table-column>
                    <el-table-column label="操作" width="300">
                        <template #default="scope">
                            <el-button link :icon="Edit" @click="handleEdit(scope)">编辑</el-button>
                            <el-button link :icon="Document" @click="handlePreview(scope)">详情</el-button><el-button link
                                :icon="Delete" @click="handleDeleteOne(scope)">删除</el-button></template>
                    </el-table-column>
                    <template #empty v-if="lowCodeStore.listAllData.tableData.length === 0"><el-empty
                            description="无数据"></el-empty></template>
                </el-table>
            </el-config-provider>
        </el-main>
        <el-footer>
            <el-config-provider :locale="zhCn">
                <el-pagination v-model:currentPage="lowCodeStore.listAllData.currentPage"
                    v-model:page-size="lowCodeStore.listAllData.pageSize" :page-sizes="[5, 10, 20, 50]" :small="small"
                    :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
                    :total="lowCodeStore.listAllData.total" @size-change="onSizeChange"
                    @current-change="onCurrentChange" />
            </el-config-provider>
        </el-footer>
    </el-container>

    <Drawer ref="drawerRef" />
    <UploadDataDialog ref="uploadDataDialogRef" />
</template>

<script setup>
import { ref, onMounted } from "vue";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import UploadDataDialog from "./dialog/uploadData.vue";
import Drawer from "./Drawer.vue";
import axios from "axios";
import {
    Edit,
    CirclePlus,
    Download,
    Upload,
    Document,
    Delete,
    Sort,
    RefreshRight,
} from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
import { fetchListTableData } from "@/api/get-data.js";
import pinia from "@/store/pinia";
import { useStore } from "@/store/lowCode.js";
const lowCodeStore = useStore(pinia);
const route = useRoute();

const drawerRef = ref(); // Drawer相关
const uploadDataDialogRef = ref(); // 数据导入Dialog
const multipleTableRef = ref();
const multipleSelection = ref([]);
let tableHeight = ref();

const tableColumns = ref([ // 字段列表
    {
        label: '用户名',
        prop: 'username',
        type: 'VARCHAR', password: false
    },
    {
        label: '密码',
        prop: 'password',
        type: 'VARCHAR',
        password: true // 假设有这个属性表示密码输入框
    },
    {
        label: '电话号码',
        prop: 'phone',
        type: 'INTEGER', password: false
    },
    {
        label: '年龄',
        prop: 'age',
        type: 'INTEGER', password: false
    },
    {
        label: '体重',
        prop: 'weight',
        type: 'DECIMAL', password: false
    },
    {
        label: '出生日期',
        prop: 'birthday',
        type: 'DATE', password: false
    },
    {
        label: '登记时间',
        prop: 'registerTime',
        type: 'DATETIME', password: false
    },
    {
        label: '描述',
        prop: 'desc',
        type: 'TEXT', password: false
    }
]);

const onSizeChange = (val) => {
    lowCodeStore.listAllData.pageSize = val;
    console.log("onSizeChange");
    console.log(val);
    fetchListTableData(modelId, lowCodeStore.listAllData.currentPage, lowCodeStore.listAllData.pageSize);
};

const onCurrentChange = (val) => {
    lowCodeStore.listAllData.currentPage = val;
    console.log("onCurrentChange");
    console.log(val);
    fetchListTableData(modelId, lowCodeStore.listAllData.currentPage, lowCodeStore.listAllData.pageSize);
};

const onSelectionChange = (val) => {
    multipleSelection.value = val;
    console.log("multipleSelection");
    console.log(multipleSelection.value);
};

const handleAdd = () => {
    drawerRef.value.visible = true;
    drawerRef.value.drawerType = "新增";
    drawerRef.value.formFields = tableColumns.value;
    drawerRef.value.ruleForm = {};
};

const handleUpload = () => {
    uploadDataDialogRef.value.visible = true;
};

const handleDownload = (scope, type) => {
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.style.height = 0;

    ElMessage("开始下载.");

    if (type === "template") {
        iframe.src = `http://192.168.0.104:8081/WordTool/word/template/download?tmCode=${scope.row.code}`;
        document.body.appendChild(iframe);
    } else if (type === "file") {
        generateWordData(scope.row.code).then((data) => {
            if (data) {
                iframe.src = `http://192.168.0.104:8081/WordTool/word/generate/download?generateInfoId=${data}`;
                document.body.appendChild(iframe);
            }
        });
    }

    setTimeout(function () {
        iframe.remove();
    }, 5 * 60 * 1000);
};

// 公共删除方法
const ajaxDelete = async (modelId, dataIdArr) => {
    // 获取字段结构
    let handleDeleteRes = await axios
        .post("/lowcode/module/custom/s", {
            "id": modelId,
            "fieldsDataList": [
                {
                    "id": dataIdArr
                }
            ]
        })
        .then((handleDeleteRes) => [null, handleDeleteRes])
        .catch((err) => [err, null]);

    console.log("预览：");
    console.log(handleDeleteRes);

    if (!handleDeleteRes[1]) {
        console.log(handleDeleteRes[1].data.message);
        ElMessage({
            message: handleDeleteRes[1].data.message,
            type: "error",
        });
        return false;
    }

    handleDeleteRes = handleDeleteRes[1];

    ElMessage({
        type: 'success',
        message: '删除成功',
    })
}

const handleDelete = () => {
    ElMessageBox.confirm(
        '确认删除选择的数据?',
        '确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            console.log("multipleSelection");
            console.log(multipleSelection.value);
            const idArr = [];
            for (let i = 0; i < multipleSelection.value.length; i++) {
                idArr.push(multipleSelection.value[i].id);
            }
            console.log("获取删除数据的id：");
            console.log(idArr);
            ajaxDelete(route.params.modelId, idArr);
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除已取消',
            })
        })
};

const handleRefresh = () => {
    console.log("刷新数据.");
}

const handleEdit = scope => {
    drawerRef.value.visible = true;
    drawerRef.value.drawerType = "编辑";
    drawerRef.value.formFields = tableColumns.value;
    for (let key in scope.row) {
        if (scope.row.hasOwnProperty(key)) {
            drawerRef.value.ruleForm[key] = scope.row[key];
        }
    }
}

const handlePreview = scope => {
    drawerRef.value.visible = true;
    drawerRef.value.drawerType = "详情";
    drawerRef.value.formFields = tableColumns.value;
    for (let key in scope.row) {
        if (scope.row.hasOwnProperty(key)) {
            drawerRef.value.ruleForm[key] = scope.row[key];
        }
    }
}

const handleDeleteOne = (scope) => {
    console.log("scope");
    console.log(scope.row);
    ElMessageBox.confirm(
        '确认删除该数据?',
        '确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            ajaxDelete(route.params.modelId, [{ id: scope.row.id }]);
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除已取消',
            })
        })
}

// 列表页：获取模型字段
const fetchModelFields = async (modelId) => {
    // 获取字段结构
    let fetchModelFieldsRes = await axios
        .post("/lowcode/module/field/get", {
            module: { "id": modelId },
        })
        .then((fetchModelFieldsRes) => [null, fetchModelFieldsRes])
        .catch((err) => [err, null]);

    console.log("预览：");
    console.log(fetchModelFieldsRes);

    if (!fetchModelFieldsRes[1]) {
        console.log(fetchModelFieldsRes[1].data.message);
        ElMessage({
            message: fetchModelFieldsRes[1].data.message,
            type: "error",
        });
        return false;
    }

    fetchModelFieldsRes = fetchModelFieldsRes[1];
}

onMounted(() => {
    tableHeight.value = window.innerHeight - 200;
    window.onresize = function () {
        tableHeight.value = window.innerHeight - 200;
    };

    fetchModelFields(route.params.modelId); // 1、获取表格字段；
    fetchListTableData(route.params.modelId, lowCodeStore.listAllData.currentPage, lowCodeStore.listAllData.pageSize); // 2、获取表格数据
});
</script>

<style lang="less" scoped>
.el-header {
    height: 50px;
    margin: 0;
    padding-top: 0;
    padding-bottom: 0;
}

.el-header-left {
    height: 50px;
    display: inline;
    float: left;
    overflow: hidden;
}

.el-header-right {
    height: 50px;
    display: inline;
    float: right;
    text-align: right;
}

.el-main {
    height: calc(100vh - 200px) !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
}

.el-footer {
    height: 40px;
    padding-top: 15px !important;
}
</style>
